//
//  DLCImagePickerController.m
//  iOS-CtrlV
//
//  Created by 龚 杰 on 12-12-30.
//  Copyright (c) 2012年 Wang Li. All rights reserved.
//

#import "DLCImagePickerController.h"
#import "BusinessOperation.h"
#import <QuartzCore/QuartzCore.h>

static NSOperationQueue*  _OperationQue;
@interface DLCImagePickerController ()

@end

@implementation DLCImagePickerController
@synthesize delegate;
@synthesize RootuUIViewController = m_RootuUIViewController;
@synthesize Size = m_Size;

- (id)init
{
    if (self = [super init]) {
        if(_OperationQue == nil){
            _OperationQue = [[NSOperationQueue alloc] init];
            [_OperationQue setMaxConcurrentOperationCount:2];
        }
    }
    return self;
}

- (void)CreateCamera
{
    if (m_picker!=nil) {
        [m_picker release];
    }
    m_picker = [[UIImagePickerController alloc]init];
    m_picker.sourceType = UIImagePickerControllerSourceTypeCamera;
//#if TARGET_IPHONE_SIMULATOR
//     m_picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//#else
//    m_picker.sourceType = UIImagePickerControllerSourceTypeCamera;
//#endif
    
    m_picker.delegate = self;
    [m_picker.view sizeToFit];
    m_picker.showsCameraControls = NO;
    
    m_flash = [UIButton buttonWithType:UIButtonTypeCustom];
    m_flash.frame = CGRectMake(15, 15, 22, 26);
    [m_flash addTarget:self action:@selector(changeFlash) forControlEvents:UIControlEventTouchUpInside];
    [m_flash setImage:[UIImage imageNamed:@"flash-off.png"] forState:UIControlStateNormal];
    [m_picker.view addSubview:m_flash];
    
    m_lens = [UIButton buttonWithType:UIButtonTypeCustom];
    m_lens.frame = CGRectMake(m_picker.view.frame.size.width-60, 15, 48, 24);
    [m_lens addTarget:self action:@selector(changeLens) forControlEvents:UIControlEventTouchUpInside];
    [m_lens setImage:[UIImage imageNamed:@"front-camera.png"] forState:UIControlStateNormal];
    [m_picker.view addSubview:m_lens];
    
    
    UIView* iview = [[UIView alloc] initWithFrame:CGRectMake(0, m_picker.view.frame.size.height-53, 320, 55)];
    [iview setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"photo_bar.png"]]];
    
    
    m_cancel  = [UIButton buttonWithType:UIButtonTypeCustom];
    m_cancel.frame = CGRectMake(10, 16, 22, 21);
    [m_cancel addTarget:self action:@selector(changeCancel) forControlEvents:UIControlEventTouchUpInside];
    [m_cancel setImage:[UIImage imageNamed:@"close.png"] forState:UIControlStateNormal];
    [iview addSubview:m_cancel];
    
    m_plibrary  = [UIButton buttonWithType:UIButtonTypeCustom];
    m_plibrary.frame = CGRectMake(m_picker.view.frame.size.width - 38, 14, 28, 28);
    [m_plibrary addTarget:self action:@selector(changeLibrary) forControlEvents:UIControlEventTouchUpInside];
    [m_plibrary setImage:[UIImage imageNamed:@"library.png"] forState:UIControlStateNormal];
    [iview addSubview:m_plibrary];
    
    m_Picture  = [UIButton buttonWithType:UIButtonTypeCustom];
    m_Picture.frame = CGRectMake(m_picker.view.frame.size.width/2-50, 6, 101, 41);
    [m_Picture addTarget:self action:@selector(shootingPicture) forControlEvents:UIControlEventTouchUpInside];
    [m_Picture setImage:[UIImage imageNamed:@"camera-icon.png"] forState:UIControlStateNormal];
    [m_Picture setBackgroundImage:[UIImage imageNamed:@"camera-button.png"] forState:UIControlStateNormal];
    [iview addSubview:m_Picture];
    
    m_picker.cameraOverlayView = iview;
    [m_RootuUIViewController presentModalViewController:m_picker animated:YES];
    [iview release];
    islens = YES;
    isflash = YES;
}

- (void)changeFlash
{
    if (isflash) {
        m_picker.cameraFlashMode = UIImagePickerControllerCameraFlashModeOn;
            [m_flash setImage:[UIImage imageNamed:@"flash-auto.png"] forState:UIControlStateNormal];
        isflash = NO;
    }else{
        m_picker.cameraFlashMode = UIImagePickerControllerCameraFlashModeOff;
            [m_flash setImage:[UIImage imageNamed:@"flash-off.png"] forState:UIControlStateNormal];
        isflash = YES;
    }
}
- (void)changeLens
{
    if (islens) {
        m_picker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
        islens = NO;
    }else{
        m_picker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
        islens = YES;
    }
}
- (void)changeCancel
{
    [m_picker dismissModalViewControllerAnimated:YES];
}
- (void)changeLibrary
{
    [m_picker dismissModalViewControllerAnimated:NO];
    [m_picker release];
    m_picker = [[UIImagePickerController alloc] init];
	m_picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    //	picker.mediaTypes = [NSArray arrayWithObject:(NSString *)kUTTypeMovie];
	m_picker.delegate = self;
	[m_picker.view sizeToFit];
	[m_RootuUIViewController presentModalViewController:m_picker animated:YES];
}
- (void)shootingPicture
{
    [m_picker takePicture];
}
#pragma mark -
#pragma mark UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    if (info !=nil) {
        BusinessOperation *businessOperation = [[BusinessOperation alloc] init];
        businessOperation.target = self;
        businessOperation.object = info;
        businessOperation.selector = @selector(asyReadFileImg:);
        [_OperationQue addOperation:businessOperation];
        [businessOperation release];
    }
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
	[picker dismissModalViewControllerAnimated:YES];
}

-(void) asyReadFileImg:(NSDictionary *)dictionary
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
   	UIImage *img = nil;
    img = [dictionary objectForKey:UIImagePickerControllerEditedImage]; //原始图片
    if (img == nil) {
        img = [dictionary objectForKey:UIImagePickerControllerOriginalImage];
    }
    UIImage* img1 = [self fixOrientation:img];
//    if (img.size.width > 640) {
//        img1 = [self scaleFromImage:img toSize:m_Size];
//    }else{
//        img1 = img;
//    }
  
    [self performSelectorOnMainThread:@selector(getImage:) withObject:img1 waitUntilDone:YES];
    [pool drain];
}
- (void)getImage:(UIImage*)image;
{
    if (delegate != nil) {
        [delegate GatimagePickerController:image picker:m_picker];
    }
}

- (UIImage *) scaleFromImage: (UIImage *) image toSize: (CGSize) size
{
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
- (UIImage *)fixOrientation:(UIImage *)aImage {
    
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}
- (void)dealloc
{
    [m_picker release];
    m_flash = nil;
    m_lens = nil;
    m_cancel = nil;
    m_plibrary = nil;
    m_Picture = nil;
    [m_RootuUIViewController release];
    [super dealloc];
}
@end
